<?php
namespace app\attendance\controller;

use app\api\Controller;
use think\Db;
use app\api\Base;
use think\Exception;
/**
 * 公共上传控制器类
 * 继承了图片，文件上传方法 包括一些业务逻辑的处理
 * 图片上传本地，七牛云
 */
class Upload extends Base
{
	/**
     * 文件上传本地
     */
    public function upload()
    {
    	$msg = ['code'=>400, 'msg'=>'上传失败', 'data'=>[]];
        $file = $this->request->file('file');
        $path = ROOT_PATH . 'public/tmp/uploads/';
        $info = $file->move($path);
        if (!$info) {
        	$msg['msg'] = $file->getError();
            return json_encode($msg);
        }
        $data = $this->request->root() . '/tmp/uploads/' . $info->getSaveName();
        $insert = [
            'cate'     => 3,
            'name'     => $data,
            'original' => $info->getInfo('name'),
            'domain'   => '',
            'type'     => $info->getInfo('type'),
            'size'     => $info->getInfo('size'),
            'mtime'    => time(),
        ];
        Db::name('File')->insert($insert);

        $msg['code'] = 200;
        $msg['msg']= '上传成功';
        $msg['data'] = $data;

        return json_encode($msg);
    }

    /**
     * 文件上传到七牛云
     */
    public function qiniuUploadfile()
    {

    	$msg = ['code'=>400, 'msg'=>'上传到七牛云失败', 'data'=>[]];
        $result = \Qiniu::instance()->upload();//七牛上传

        $url=config("qiniu.QINIU_DOMAIN").$result[0]['key'];

        $insert = [
            'cate'     => 3,
            'name'     => $url,
            'original' => $result[0]['name'],
            'domain'   => config("qiniu.QINIU_DOMAIN"),
            'type'     => $result[0]['type'],
            'size'     => $result[0]['size'],
            'mtime'    => time(),
        ];
   		$msg['code'] = 200;
   		$msg['msg'] = "上传成功";
   		$msg['data'] = ['url'=>$url, 'name'=>$result[0]['name']]; 
       return json_encode($msg);
    }
    /**
    * qiniu多图上传
    */
   public function qiniuManyUploadfile(){
        #上传图片
        $photo = [];
        $result = \Qiniu::instance()->upload(); //七牛上传
        if ($result){
            foreach ($result as $photoValues){
                $photo[] = config('qiniu.QINIU_DOMAIN') . $photoValues['key'];
            }
        }
        return $photo;
   }

   /**
    * 人员导入
    * 第一步：上传execl到服务器
    * 模板下载地址：/tmp/user.xlsx
    */
    public function uploadUserOne()
    {

        $msg = ['code'=>400, 'msg'=>'上传execl失败' , 'data'=>[]]; 
        $file = $this->request->file('file'); 
        try{
            $fileinfo = $file->getInfo();
            $mtRandUrl = 'user'.date('Ymd',time()).mt_rand(10000,99999).'/';
            $path = ROOT_PATH.'public/tmp/uploads/user/'.$mtRandUrl;
            $info = $file->move($path, $fileinfo['name']);
            $url = './tmp/uploads/user/'.$mtRandUrl.$info->getSaveName(); 
            if($url){
                $msg['code'] = 200;
                $msg['msg'] = '上传成功';
                $msg['data'] = ['url'=>$url,'current'=>1];
            }   
        }catch(Exception $ex){
            $msg['msg'] = $ex->getMessage();
        }
        return json_encode($msg);
    }
    /**
     * 人员导入
     * 第二步：解析数据 导入到数据库
     * 模板下载地址：/tmp/user.xlsx
     */ 
    public function uploadUserTwo()
    {
        $msg = ['code'=>400, 'msg'=>'导入人员失败，请检查execl格式是否有特殊字符', 'data'=>['current'=>2]];
        $execlUrl = $this->request->param('url') ? $this->request->param('url') :""; #execl的路径
        $platformId = $this->request->param('platformId')?$this->request->param('platformId'):""; # 平台id
        $adminUserId = $this->request->param('adminUserId')?$this->request->param('adminUserId'):""; # 后台管理员adminUserId
        $adminReg = $this->request->param('adminReg') ? getStr($this->request->param('adminReg')) : ''; #后台管理员adminReg
        //var_dump($execlUrl);exit;
        // 不确定参数
        $unitsId = $this->request->param('unitsId') ? getStr($this->request->param('unitsId')) : '0'; #单位id 单位id==部门id
        $positionId =$this->request->param('positionId') ? getStr($this->request->param('positionId')) : '0'; #职位id 如果没有就读execl

        // 默认密码
        $defaultPassword = "123456";

        if(empty($execlUrl)){$msg['msg']="Execl未上传，请重新上传"; return json_encode($msg);}
        if(empty($platformId)){$msg['msg']="请选择相应平台"; return json_encode($msg);}
        if(empty($unitsId)){$msg['msg']="请先选择要导入的单位"; return json_encode($msg);}
        //if(empty($positionId)){$msg['msg']="请选择需要人员职位"; return json_encode($msg);}

        // 通过文件上传，然后取到上传后的完整路径文件名
        // 解析 Excel 头部信息，返回 $excelHeader = ['A' => '第一行A列描述', 'B' => '第一行B列描述', 'C' => '第一行C列描述',...]
        // # A:姓名 B:工号 C:身份证 D:手机号 E:密码 F：是否主管
        try{ 

            $excelHeader = \Excel::parseHeader($execlUrl);
            $header = ['A' => 'realName', 'B' => 'jobNumber', 'C' => 'idcard', 'D' => 'phone', 'E' => 'password', 'F' => 'isCharge'];
             # 开启事务一个错误全部回滚
             Db::startTrans();

             try{
                 $result = \Excel::parse($execlUrl, $header, 20, function ($data) {
                    # 可以在此处对数据进行过滤处理，例如： 
                    foreach ($data as &$v) {
                        // var_dump($data);die;
                        #拼音账号
                        $username = \CUtf8PY::encode($v['realName'],'all');
                        $v['userName'] = $username.mt_rand(10000,99999);

                        #姓名
                        $v['realName'] = $v['realName'];

                        #工号
                        $v['jobNumber'] = $v['jobNumber'];

                        #密码
                        if(empty($v['password'])){
                            #为空取默认
                            $v['passsalt'] = $this->random(8);
                            $v['showPassword'] = $defaultPassword;
                            $v['password'] = $this->dpassword($defaultPassword, $v['passsalt']);
                        }else{
                            $v['passsalt'] = $this->random(8);
                            $v['showPassword'] = $v['password'];
                            $v['password'] = $this->dpassword($v['password'], $v['passsalt']);
                        }

                        #身份证
                        if(empty($v['idcard'])){ 
                            $v['idcard'] = ""; 
                        }else{
                            $v['idcard'] = @str_replace('#','',$v['idcard']);
                        }

                        #手机号
                        if(empty($v['phone'])){ 
                            $v['phone']=""; 
                            $v['isBind'] = 2;
                        }else{
                            $v['phone']= $v['phone']; 
                            $v['isBind'] = 1;
                        }

                        #是否主管
                        if(empty($v['isCharge'])){
                            $v['isCharge'] = 2;
                        }else{
                            if($v['isCharge']==1){
                                $v['isCharge'] = 1;  
                            }else{
                                $v['isCharge'] = 2;    
                            }
                        }

                        #单位 or 部门
                        $v['unitId'] = $this->request->param('unitsId') ? getStr($this->request->param('unitsId')) : '0'; #单位id 单位id==部门id
                        $v['departmentId'] = $this->request->param('unitsId') ? getStr($this->request->param('unitsId')) : '0'; #单位id 单位id==部门id
                        #平台
                        $v['platformId'] = $this->request->param('platformId')?$this->request->param('platformId'):""; # 平台id
                        #创建时间
                        $v['createTime'] = time();
                        #状态
                        $v['status'] = 2;
                        #照片 和 状态错误点击恢复
                        $v['photoStatus'] = 4;
                        #职位
                        $v['positionId'] = $this->request->param('positionId') ? getStr($this->request->param('positionId')) : '0'; #职位id 如果没有就读execl
                        $v['photo'] = ""; #默认照片为空

                        //逐条写入数据库
                        if($v['realName'] && $v['jobNumber']){
                            $ret = Db::connect("db_config_attendance")->name('member')->insert($v, FALSE, TRUE);         
                        }
                        #查询是否有重复存在的工号手机号和身份证
                        // if(!empty($v['phone'])){
                        //     $phoneWhere['phone'] = $v['phone'];
                        //     $emptyUserId = Db::connect("db_config_attendance")->name('member')->where($phoneWhere)->field("id")->find();
                        //     if(!empty($emptyUserId)){
                        //         Db::rollback();
                        //         $msg['msg'] = "手机号".$v['phone']."已存在";
                        //         return json_encode($msg);
                        //     }    
                        // }
                        // if(!empty($v['jobNumber'])){
                        //     $jobWhere['jobNumber'] = $v['jobNumber'];
                        //     $emptyUserId = Db::connect("db_config_attendance")->name('member')->where($jobWhere)->field("id")->find();
                        //     if(!empty($emptyUserId)){
                        //         Db::rollback();
                        //         $msg['msg'] = "工号".$v['jobNumber']."已存在";
                        //         return json_encode($msg);
                        //     }
                        // }
                        // if(!empty($v['idcard'])){
                        //     $idcardWhere['idcard'] = $v['idcard'];
                        //     $emptyUserId = Db::connect("db_config_attendance")->name('member')->where($idcardWhere)->field("id")->find();
                        //     if(!empty($emptyUserId)){
                        //         Db::rollback();
                        //         $msg['msg'] = "身份证".$v['idcard']."已存在";
                        //         return json_encode($msg);
                        //     }
                        // }
                        
                    }
                }); 
                
                $msg['code'] = 200;
                $msg['data'] = ['current'=>3];
                $msg['msg'] = "导入人员成功";
                // 提交事务
                Db::commit();

            }catch(Exception $ex){
                # 回滚直接报错
                 // $msg['msg'] = $ex->getMessage();
                $msg['msg'] = "提示：导入人员失败，请依照模板认真检查execl格式!";
                Db::rollback();
                $msg['code'] = 400;
                
                return json_encode($msg);
            }

        }catch(Exception $e){
             // $msg['msg'] = $e->getMessage();
            $msg['msg'] = "导入人员失败，请依照模板认真检查execl格式!";
            $msg['code'] = 400;
            Db::rollback();
            
        }

        return json_encode($msg);
    }
    // 用户导入 返回一个盐
    private function random($length, $type = 0, $hash = ''){
        if ($type == 0) {
            $chars = '0123456789abcdefghijklmnopqrstuvwxyz';
        } else if ($type == 1) {
            $chars = '0123456789';
        } else if ($type == 2) {
            $chars = 'abcdefghijklmnopqrstuvwxyz';
        }
        $max = strlen($chars) - 1;
        mt_srand((double) microtime() * 1000000);
        for ($i = 0; $i < $length; $i++) {
            $hash .= $chars[mt_rand(0, $max)];
        }
        return $hash;
    }
    // 生成密码
    private function dpassword($password, $salt){
        return md5((preg_match("/^[a-f0-9]{32}$/", $password) ? md5($password) : md5(md5($password))) . $salt);
    }

}